define(['jquery', 'domReady!', 'appLocalStorage', 'appConst', 'model/global', 'model/project', 'stringUtils', 'datetimepicker/datetimepicker'], function ($, domReady, appLocalStorage, appConst, globalM, projectM, stringUtils) {
    var searchFields = {};
    var projectDS;
    var stationDS;
    var slotDS;
    var snDS;
    var components = {};
    var that;
    var searchBarKey = {
        "fields": "searchbar.search.fields",
        "ds": "searchbar.search.ds"
    };
    var listeners = {
        'initCompleted': function () {
        }
    };
    var isRead = {
        project: true,
        station: true,
        slot: true,
        allTrue: function () {
            isRead.project = true;
            isRead.station = true;
            isRead.slot = true;
        }
    };
    return {
        init: function () {
            that = this;
            components = {
                "project": $('#searchbar').find('#slt_sb_project'),
                "station": $('#searchbar').find("#slt_sb_station"),
                "slot": $('#searchbar').find("#slt_sb_slot"),
                "sn": $('#searchbar').find("#txt_sb_serialNumber"),
                "startTime": $('#searchbar').find('#dtp_sb_startTime'),
                "stopTime": $('#searchbar').find('#dtp_sb_stopTime'),
                "searchBtn": $('#searchbar').find('#btn_sb_searchBtn'),
                "alt_sb_searchAlert": $('#searchbar').find('#alt_sb_searchAlert')
            };
            isRead.allTrue();

            that.initProject();
            that.initStation();
            that.initSlot();
            that.initDateTime();

            that.bindSearchEvent();
            that.reloadProject(function () {
                that.matchLocalSearchFieldData();
                listeners.initCompleted();
            });
        },
        initProject: function (callback) {
            projectDS = [];
            components.project.select2({
                id: function (rs) {
                    return rs.id;
                },
                allowClear: true,
                data: function () {
                    return {results: projectDS, text: 'name'};
                },
                formatResult: function (data) {
                    var itemFmt = "<span>" + data.name == null ? '' : data.name + "</span>";
                    return itemFmt;
                },
                formatSelection: function (data) {
                    return data.name == null ? '' : data.name;
                },
                formatMatches: function () {
                },
                formatNoMatches: function () {
                    return $.i18n.prop("GLOBAL_SELECTOR_NORESULT");
                },
                escapeMarkup: function (m) {
                    return m;
                }
            });
            components.project.on('change', function (e) {
                components.sn.val('');
                snDS = [];

                that.reloadStation();
            });
        },
        reloadProject: function (callback) {
            projectDS = [];
            projectM.searchProject(null, function (d) {
                if (d == null) {
                    return;
                }
                projectDS = d;
                if (isRead.project == true) {
                    var localSearchFields = appLocalStorage.getLocal(searchBarKey.fields);
                    if (localSearchFields != null) {
                        var localsf = JSON.parse(localSearchFields);
                        components.project.select2("val", localsf.search_projectId).trigger("change");
                    }
                    isRead.project = false;
                }
                callback();
            });

        },
        initStation: function (callback) {
            stationDS = [];
            components.station.select2({
                data: function () {
                    return {results: stationDS};
                },
                tags: true
            });
            components.station.on('change', function (e) {
                that.reloadSlot();
            });
        },
        reloadStation: function () {
            stationDS = [];
            slotDS = [];
            var pm = {
                projectId: components.project.select2('val')
            };
            components.station.select2('val', '');
            components.slot.select2('val', '');
            if (stringUtils.isBlank(pm.projectId)) {
                return;
            }
            projectM.searchStation(pm, function (d) {
                stationDS = new Array();
                $.each(d, function (i, data) {
                    stationDS.push({"id": data.stationId, "text": data.stationId, "slotNos": data.slotNos});
                });
                if (isRead.station == true) {
                    var localSearchFields = appLocalStorage.getLocal(searchBarKey.fields);

                    if (localSearchFields != null) {
                        var localsf = JSON.parse(localSearchFields);
                        if (localsf.search_projectId != pm.projectId) {
                            localsf.search_stationIds = [];
                            localsf.search_slotIds = [];
                            appLocalStorage.setLocal(searchBarKey.fields, JSON.stringify(localsf));
                        } else {
                            components.station.select2("val", localsf.search_stationIds).trigger("change");
                        }
                    }
                    isRead.station = false;
                }
            });
        },
        initSlot: function () {
            slotDS = new Array();
            components.slot.select2({
                data: function () {
                    return {results: slotDS};
                },
                tags: true,
                formatResult: function (data) {
                    var itemFmt = "<span>" + data.text + "</span>";
                    return itemFmt;
                },
                formatSelection: function (data) {
                    var itemFmt = "<span>" + data.text + "</span>";
                    return itemFmt;
                }
            });
            components.slot.on('change', function (e) {
            });
        },
        reloadSlot: function () {
            slotDS = [];
            var currentSlots = components.slot.select2('val');
            var array = components.station.select2("val");

            $.each(stationDS, function (i, station) {
                if ($.inArray(station.id, array) != -1) {
                    $.each(station.slotNos, function (i, slot) {
                        slotDS.push({
                            "id": station.id + "-" + slot,
                            "text": station.text + (slot == "" ? "" : ( "-" + slot)),
                            "rId": slot,
                            "stationId": station.id
                        });
                    });

                }
            });
            var selectSlots = [];
            $.each(currentSlots, function (i, slot) {
                var inArrays = false;
                $.each(slotDS, function (i, ds) {
                    if (slot == ds.id) {
                        selectSlots.push(slot);
                        return false;
                    }
                });
            });
            components.slot.select2('val', selectSlots);

            if (isRead.slot == true) {
                var localSearchFields = appLocalStorage.getLocal(searchBarKey.fields);
                if (localSearchFields != null) {
                    var localsf = JSON.parse(localSearchFields);
                    if (localsf.search_slotIds != null && localsf.search_slotIds.length > 0) {
                        components.slot.select2("val", localsf.search_slotIds).trigger("change");
                    }
                }
                isRead.slot = false;
            }
        },
        reloadSn: function () {
            snDS = [];
            var pm = that.getSearchParameters();
            if (stringUtils.isBlank(pm.search_projectId)) {
                return;
            }
            projectM.searchDistinctSN(pm, function (d) {
                snDS = new Array();
                $.each(d, function (i, obj) {
                    snDS.push({"id": obj, "text": obj});
                });
            });

        },
        initDateTime: function () {
            var startTime = components.startTime;
            var stopTime = components.stopTime;
            startTime.datetimepicker({
                format: $.i18n.prop('APP_DATE_FORMAT_TIMEPICKER'),
                // language: 'zh_CN',
                autoclose: true,
                todayBtn: true,
                prevText: '<i class="fa fa-chevron-left"></i>',
                nextText: '<i class="fa fa-chevron-right"></i>'
            });

            startTime.on('change', function () {
                var date = startTime.datetimepicker('getDate');
                var stop = stopTime.datetimepicker('getDate');
                if (date > stop) {
                    stopTime.val('');
                }
                stopTime.datetimepicker('setStartDate', date);
            });

            stopTime.datetimepicker({
                format: $.i18n.prop('APP_DATE_FORMAT_TIMEPICKER'),
                autoclose: true,
                todayBtn: true,
                prevText: '<i class="fa fa-chevron-left"></i>',
                nextText: '<i class="fa fa-chevron-right"></i>'
            });
            stopTime.on('change', function () {
                var date = startTime.datetimepicker('getDate');
                var stop = stopTime.datetimepicker('getDate');
                if (date > stop) {
                    startTime.val('');
                    stopTime.datetimepicker('setStartDate', null);
                }
            });
        },
        bindSearchEvent: function (listener) {
            components.searchBtn.unbind('click');

            components.searchBtn.click(function (e) {
                if (components.project.select2('data') == null) {
                    components.alt_sb_searchAlert.fadeIn(200);
                    return;
                }
                components.alt_sb_searchAlert.fadeOut(200);
                that.setConditionsToLocalStorage();

                if ((typeof listener) == 'function') {
                    listener(searchFields);
                }
            });
        },
        onCompleted: function (listener) {
            if (typeof listener == "function") {
                listeners.initCompleted = listener;
            }
        },
        doSearch: function () {
            components.searchBtn.trigger("click");
        },
        matchLocalSearchFieldData: function () {
            var localSearchFields = appLocalStorage.getLocal(searchBarKey.fields);
            if (localSearchFields != null) {
                var localsf = JSON.parse(localSearchFields);
                // components.project.select2("val", localsf.search_projectId).trigger("change");
                // components.station.select2("val", localsf.search_stationIds).trigger("change");
                // components.slot.select2("val", localsf.search_slotIds);
                components.sn.val(localsf.search_serialNumber);
                components.startTime.val(localsf.search_startTime);
                components.stopTime.val(localsf.search_stopTime);
            }
        },
        getSearchParameters: function () {
            var searchParam = {
                'search_projectId': components.project.select2('val'),
                'search_projectName': components.project.select2('data') != null ? components.project.select2('data').name : "",
                'search_stationIds': components.station.select2('val'),
                'search_slotIds': components.slot.select2('val'),
                'search_serialNumber': components.sn.val(),
                'search_startTime': components.startTime.val(),
                'search_stopTime': components.stopTime.val()
            };

            var stations = new Array();
            $.each(searchParam.search_stationIds, function (i, sobj) {
                var s = {'stationId': sobj, 'slotNos': []};
                $.each(searchParam.search_slotIds, function (i, slotObj) {
                    var stationName = that.getSplitDataFromSlot(slotObj).station;
                    var slotName = that.getSplitDataFromSlot(slotObj).slot;
                    if (sobj == stationName) {
                        s.slotNos.push(slotName);
                    }
                });
                stations.push(s);
            });
            searchParam.search_stationIdOrSlotNo = JSON.stringify(stations);

            searchFields = searchParam;
            return searchParam;
        },
        setConditionsToLocalStorage: function (key) {
            // var stationIds = components.station.select2('val');
            var searchParam = that.getSearchParameters();
            appLocalStorage.setLocal(searchBarKey.fields, JSON.stringify(searchParam));

            var localDS = {
                stationDS: stationDS,
                slotDS: slotDS
            };
            appLocalStorage.setLocal(searchBarKey.ds, JSON.stringify(localDS));
        },
        getSearchFields: function () {
            return searchFields;
        },
        getCurrentChoiceProjectId: function () {
            return components.project.select2('val');
        },
        getProjectDS: function () {
            return projectDS;
        },
        getStationDS: function () {
            return stationDS;
        },
        getSlotDS: function () {
            return slotDS;
        },
        getSnDS: function () {
            return snDS;
        },
        getLocalStorageDS: function () {
            var localSearchFields = appLocalStorage.getLocal(searchBarKey.ds);
            var localsf = JSON.parse(localSearchFields);
            return localsf;
        },
        getSplitDataFromSlot: function (slot) {
            var stationName = slot.substring(0, slot.lastIndexOf("-"));
            var slotText = slot.substring(slot.lastIndexOf("-") + 1, slot.length);
            return {'station': stationName, 'slot': slotText};
        },
        setFieldsValue: function (obj) {
            var defaultP = {
                "startTime": "",
                "endTime": ""
            };
            if (obj == null) {
                return;
            }
            var param = $.extend({}, defaultP, obj);

            if (stringUtils.isNotBlank(param.startTime)) {
                components.startTime.val(param.startTime);
            }
            if (stringUtils.isNotBlank(param.endTime)) {
                components.stopTime.val(param.endTime);
            }
            that.setConditionsToLocalStorage();
        }
    }
});